package com.kumi.shop.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.kumi.common.to.es.SkuEsModel;
import com.kumi.shop.search.config.ElasticSearchConfig;
import com.kumi.shop.search.constant.EsConstant;
import com.kumi.shop.search.service.MallSearchService;
import com.kumi.shop.search.vo.SearchParam;
import com.kumi.shop.search.vo.SearchRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.fetch.subphase.highlight.Highlighter;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchRes search(SearchParam param) {
        SearchRes res = null;
        SearchRequest searchRequest = buildSearchRequrest(param);

        try {
            SearchResponse search = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            res = buildSearchRes(search,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    private SearchRes buildSearchRes(SearchResponse search,SearchParam param) {
        SearchRes searchRes = new SearchRes();
        SearchHits hits = search.getHits();
        List<SkuEsModel> list = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string );
                }
                list.add(skuEsModel);
            }
        }

        searchRes.setProducts(list);
        List<SearchRes.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = search.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");

        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchRes.AttrVo attrVo = new SearchRes.AttrVo();
            long key = bucket.getKeyAsNumber().longValue();
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(key);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchRes.setAttrs(attrVos);

        List<SearchRes.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = search.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchRes.BrandVo brandVo = new SearchRes.BrandVo();
            long key = bucket.getKeyAsNumber().longValue();
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(key);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchRes.setBrands(brandVos);

        ParsedLongTerms catalog_agg = search.getAggregations().get("catalog_agg");
        List<SearchRes.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchRes.CatalogVo catalogVo = new SearchRes.CatalogVo();
            String key = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(key));
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        searchRes.setCatalogs(catalogVos);

        searchRes.setPageNum(param.getPageNum());

        long total = hits.getTotalHits().value;
        searchRes.setTotal(total);

        int totalPages = (int)total%EsConstant.PRODUCT_PAGESIZE == 0 ? (int)total/EsConstant.PRODUCT_PAGESIZE:(int)(total/EsConstant.PRODUCT_PAGESIZE + 1);
        searchRes.setTotalPages(totalPages);
        return searchRes;
    }

    private SearchRequest buildSearchRequrest(SearchParam param) {
        SearchSourceBuilder source = new SearchSourceBuilder();
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getKeyword())){
            query.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        if (param.getCatalog3Id() != null){
            query.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0){
            query.filter(QueryBuilders.termQuery("brand",param.getBrandId()));
        }

        if (param.getAttrs() != null && param.getAttrs().size() > 0){

            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nestedbool = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedbool.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedbool.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder attrs = QueryBuilders.nestedQuery("attrs", nestedbool, ScoreMode.None);
                query.filter(attrs);
            }
        }

        if(null != param.getHasStock()){
            query.filter(QueryBuilders.termQuery("hasStock",param.getHasStock() == 1));
        }

        if (!StringUtils.isEmpty(param.getSkuPrice())){
            RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2){
                rangeQueryBuilder.gte(s[0]).lte(s[1]);
            }else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(s[0]);
                }
                if (param.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.gte(s[0]);
                }
            }
            query.filter(rangeQueryBuilder);
        }
        source.query(query);

        if (!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equals("asc")?SortOrder.ASC:SortOrder.DESC;
            source.sort(s[0], order);
        }
        source.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        source.size(EsConstant.PRODUCT_PAGESIZE);
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            source.highlighter(builder);
        }

        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size();
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        source.aggregation(brand_agg);

        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName")).size(1);
        source.aggregation(catalog_agg);

        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        source.aggregation(attr_agg);

        //log.info("构建的DSL语句 {}",source.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, source);
        return searchRequest;
    }








}
